﻿//===============================================================================
// Magic OQL
//===============================================================================
// Copyright ?Magic Thought Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// Richie (http://www.cnblogs.com/RicCC)
// March 7, 2008
//===============================================================================

using System.Text;
using Antlr.Runtime;
using Antlr.Runtime.Tree;

namespace Magic.Framework.OQL.Expressions
{
    /// <summary>
    /// These expressions are simply treated as text nodes.
    /// </summary>
    /// <remarks>
    /// The differences between CombinedKeywords and Text is that CombinedKeywords may have
    /// subtree expressions, but none for Text.
    /// </remarks>
    public class Text : CombinedKeywords
    {
        private bool _delim = true;
        private string _delimiter = " ";

        public Text(IToken t)
            : base(t, (t.Type == SQLParser.TextNode ? "" : t.Text), false, null, true, null)
        {
        }
        public Text(IToken t, string s, bool delim, string delimiter)
            : base(t, s, false, null, true, null)
        {
            this._delim = delim;
            this._delimiter = delimiter;
        }
        public Text(Text text)
            : this(text.Token, text.Text, text._delim, text._delimiter)
        {
        }

        /// <summary>
        /// Ignore all child expressions except the , append their text to this one.
        /// </summary>
        /// <param name="s"></param>
        protected override bool PreCombine(int count, StringBuilder builder, IToken token)
        {
            if (this._delim && count > 0) builder.Append(this._delimiter);
            return true;
        }
        public override Expression DupNode()
        {
            return new Text(this);
        }

        public override void VisitSql(ISqlVisitor visitor)
        {
            visitor.Sql(this.ToString());
        }

        internal static int TreeType
        {
            get
            {
                return SQLParser.TextNode;
            }
        }
        public static bool IsText(Expression exp)
        {
            if (exp == null || exp.IsNil) return false;
            return exp.Token.Type == SQLParser.TextNode || (exp is Text);
        }
    }
}